﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.employee;
using BenCaoXuan.Infrastructure.Dto.PC;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Redis;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.EFCore;
using BenCaoXuan.Service.Interface.PC;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using ServiceStack.Script;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.PC
{
    [Inject_]
    public class Main_Service : Base_Service, I_Main_Service
    {
        private readonly Appointment_IOC _appointment_IOC;
        private readonly Product_IOC _product_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Order_IOC _order_IOC;
        private readonly Customer_IOC _customer_IOC;
        private readonly Sys_IOC _sys_IOC;
        private readonly Arrange_IOC _arrange_IOC;

        public Main_Service(Appointment_IOC appointment_IOC, Product_IOC product_IOC, Login_IOC login_IOC, Order_IOC order_IOC, Customer_IOC customer_IOC, Sys_IOC sys_IOC, Arrange_IOC arrange_IOC)
        {
            _appointment_IOC = appointment_IOC;
            _product_IOC = product_IOC;
            _login_IOC = login_IOC;
            _order_IOC = order_IOC;
            _customer_IOC = customer_IOC;
            _sys_IOC = sys_IOC;
            _arrange_IOC = arrange_IOC;
        }

        /// <summary>
        /// 新增预约
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Appointment(Appointment_Dto dto)
        {

            Appointment appointment = new Appointment()
            {
                AId = Config.GenerateTId(),
                ACustomerId = dto.c_id,
                ACustomerName = dto.c_name,
                APhone = dto.c_phone,
                AProductId = dto.p_sid,
                APackageId = dto.p_pid,
                ATime = dto.time,
                APeriod = Convert.ToDateTime(dto.period),
                AMoney = Convert.ToDouble(dto.money),
                AStatus = 0,
                AIsOrder = 0,
                AVisit = 0,
            };

            _appointment_IOC._appointment_EFCore.Add(appointment);
            var result = await _appointment_IOC._appointment_EFCore.SaveChangesAsync();

            return Get_Result(result == 1 ? 1 : -1, result == 1 ? "预约成功" : "预约失败");
        }

        /// <summary>
        /// 完成支付
        /// </summary>
        /// <param name="pay_id"></param>
        /// <param name="o_id"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        //public bool PayMent(string pay_id, string o_id, string money)
        //{
        //    OrderPayment payment = new OrderPayment()
        //    {
        //        OpId = pay_id,
        //        OpOid = o_id,
        //        OpCreateTime = DateTime.Now,
        //        OpMoney = Convert.ToDouble(money),
        //    };
        //    var order = _order_IOC._orders_EFCore.GetAll(d => d.OId == o_id).SingleOrDefault();
        //    if (order == null)
        //    {
        //        return false;
        //    }
        //    order.OStatus = 1;
        //    order.OCreateTime = DateTime.Now;
        //    _orderIOC._order_EFCore.Update(order);
        //    _orderIOC._order_Payment_EFCore.Add(payment);
        //    var result = _orderIOC._order_Payment_EFCore.Transactions(_orderIOC._order_EFCore);
        //    return result;

        //}


        /// <summary>
        /// 新增客户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Customs(Customs_Dto dto)
        {
            Custom _custom = new Custom()
            {
                CId = Config.GenerateCustomerNo(),
                CName = dto.name + (dto.gender == 0 ? "女士" : "先生"),
                CCreateTime = DateTime.Now,
                CIsConvert = 0,
                CPassword = "FB9EFF034A33B636062213D97F00E5",//密码
                CPhone = dto.phone,
                CRemark = "",
                CResource = "04091b0603e500200f4c860feb991a48",//客户来源 字典表id
                CSalt = "616A355C16B4430594FF94BC04D893E7",//盐
                CStatus = 2,
                CUpdateTime = DateTime.Now,
            };

            _customer_IOC._customer_EFCore.Add(_custom);
            await _customer_IOC._customer_EFCore.SaveChangesAsync();

            return Get_Result(1, "ok");
        }

        /// <summary>
        /// 直接生成订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Order(string id, Orders_Dto dto)
        {
            try
            {
                // 先验证数据
                var room_iq = await _order_IOC._room_EFCore.GetAll(d => d.RId == dto.r_id).SingleOrDefaultAsync();
                if (room_iq == null) return Get_Result(0, "房间不存在");

                var employee_iq = await _login_IOC._sysEmployee_EFCore.GetAll(d => d.EId == dto.e_id).SingleOrDefaultAsync();
                if (employee_iq == null) return Get_Result(0, "理疗师不存在");

                // 创建订单
                Order _order = new Order()
                {
                    OId = Config.GenerateOrderId(),
                    OCreateTime = DateTime.Now,
                    OCustomerId = dto.c_id,
                    OCustomerName = dto.c_name,
                    OCustomerPhone = dto.c_phone,
                    OEmployeeArtId = dto.e_id,
                    OEmployeeFrontId = id,
                    OIsAppointment = 0,
                    OCompleteTime = DateTime.Now,
                    OOrderStatus = 0,
                    OPayStatus = 0,
                    OPayType = "",
                    ORoomId = dto.r_id,
                    OTotalAmount = Convert.ToDecimal(dto.money),
                };

                _order_IOC._orders_EFCore.Add(_order);

                // 必须先保存订单，才能获取订单ID用于订单详情
                await _order_IOC._orders_EFCore.SaveChangesAsync();

                var vip = _customer_IOC._customerVip_EFCore.GetAll(d => d.CvCustomerId == dto.c_id);
                if (!vip.Any())
                {
                    CustomerVip _customerVip = new CustomerVip()
                    {
                        CvId = Config.GUID(),
                        CvCreateTime = DateTime.Now,
                        CvCustomerId = dto.c_id,
                        CvExpireTime = null,
                        CvGetTime = DateTime.Now,
                        CvOperatorId = id,
                        CvPoint = Convert.ToDecimal(dto.money),
                        CvRemark = "",
                        CvStatus = 1,
                        CvVipcode = null,
                    };

                    _customer_IOC._customerVip_EFCore.Add(_customerVip);

                    var customs=await _customer_IOC._customer_EFCore.GetAll(d=>d.CId== dto.c_id).SingleAsync();

                    customs.CStatus = 1;
                    customs.CIsConvert = 1;
                    customs.CUpdateTime= DateTime.Now;
                    _customer_IOC._customer_EFCore.Update(customs);
                    await _customer_IOC._customer_EFCore.SaveChangesAsync();
                }
                else
                {
                    var vip_add = vip.Single();
                    vip_add.CvPoint += Convert.ToDecimal(dto.money);

                    _customer_IOC._customerVip_EFCore.Update(vip_add);
                }

                await _customer_IOC._customerVip_EFCore.SaveChangesAsync();


                // 创建订单详情
                OrderDetail orderDetail = new OrderDetail()
                {
                    OdId = Config.GUID2(),
                    OdOrderId = _order.OId, // 这里需要订单保存后的ID
                    OdPackageId = dto.pp_id,
                    OdProductId = dto.ps_id,
                };

                // 更新房间状态
                room_iq.RCurrentOccupancy += 1;
                if (room_iq.RCurrentOccupancy == room_iq.RTotalBeds)
                {
                    room_iq.RStatus = 1;
                }

                // 更新理疗师状态
                employee_iq.ELeisure = 1;

                // 添加和更新其他实体
                _order_IOC._ordersDetails_EFCore.Add(orderDetail);
                _order_IOC._room_EFCore.Update(room_iq);
                _login_IOC._sysEmployee_EFCore.Update(employee_iq);

                // 保存所有剩余变更
                await _order_IOC._ordersDetails_EFCore.SaveChangesAsync();
                await _order_IOC._room_EFCore.SaveChangesAsync();
                await _login_IOC._sysEmployee_EFCore.SaveChangesAsync();

                return Get_Result(1, "ok");
            }
            catch (DbUpdateException dbEx)
            {
                return Get_Result(0, $"数据库更新错误: {dbEx.InnerException?.Message ?? dbEx.Message}");
            }
            catch (Exception ex)
            {
                return Get_Result(0, $"系统错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 修改订单服务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Amend_Order(Orders_Dto dto)
        {
            var iq = await _order_IOC._orders_EFCore.GetAll(d => d.OId == dto.id).SingleOrDefaultAsync();

            iq.OTotalAmount = Convert.ToDecimal(dto.money);

            var iq_detail = await _order_IOC._ordersDetails_EFCore.GetAll(d => d.OdOrderId == dto.id).SingleOrDefaultAsync();

            iq_detail.OdPackageId = dto.pp_id;
            iq_detail.OdProductId = dto.ps_id;

            _order_IOC._ordersDetails_EFCore.Update(iq_detail);
            _order_IOC._orders_EFCore.Update(iq);

            await _order_IOC._ordersDetails_EFCore.SaveChangesAsync();
            await _order_IOC._orders_EFCore.SaveChangesAsync();


            return Get_Result(1, "ok");

        }

        /// <summary>
        /// 预约安排成订单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Arrange_Add_Order(string id, Orders_Dto dto)
        {
            //预约
            var iq = _appointment_IOC._appointment_EFCore.GetAll(d => d.AId == dto.a_id).SingleOrDefault();

            iq.AIsOrder = 1;


            _appointment_IOC._appointment_EFCore.Update(iq);
            await _appointment_IOC._appointment_EFCore.SaveChangesAsync();

            Order _order = new Order()
            {
                OId = Config.GenerateOrderId(),
                OCompleteTime = DateTime.Now,
                OCustomerId = dto.c_id,
                OCustomerName = dto.c_name,
                OCustomerPhone = dto.c_phone,
                OEmployeeArtId = dto.e_id,
                OEmployeeFrontId = id,
                OIsAppointment = 1,
                OCreateTime = DateTime.Now,
                OOrderStatus = 0,
                OPayStatus = 0,
                OPayType = "",
                ORoomId = dto.r_id,
                OTotalAmount = Convert.ToDecimal(dto.money)
            };

            _order_IOC._orders_EFCore.Add(_order);
            await _order_IOC._orders_EFCore.SaveChangesAsync();

            var vip = _customer_IOC._customerVip_EFCore.GetAll(d => d.CvCustomerId == dto.c_id);
            if (!vip.Any())
            {
                CustomerVip _customerVip = new CustomerVip()
                {
                    CvId = Config.GUID(),
                    CvCreateTime = DateTime.Now,
                    CvCustomerId = dto.c_id,
                    CvExpireTime = null,
                    CvOperatorId = id,
                    CvGetTime = DateTime.Now,
                    CvPoint = Convert.ToDecimal(dto.money),
                    CvRemark = "",
                    CvStatus = 1,
                    CvVipcode = null,
                };

                _customer_IOC._customerVip_EFCore.Add(_customerVip);

                var customs = await _customer_IOC._customer_EFCore.GetAll(d => d.CId == dto.c_id).SingleAsync();

                customs.CStatus = 1;
                customs.CIsConvert = 1;
                customs.CUpdateTime = DateTime.Now;
                _customer_IOC._customer_EFCore.Update(customs);
                await _customer_IOC._customer_EFCore.SaveChangesAsync();

            }
            else
            {
                var vip_add = vip.Single();
                vip_add.CvPoint += Convert.ToDecimal(dto.money);

                _customer_IOC._customerVip_EFCore.Update(vip_add);
            }

            await _customer_IOC._customerVip_EFCore.SaveChangesAsync();


            OrderDetail _orderDetail = new OrderDetail()
            {
                OdId = Config.GUID2(),
                OdOrderId = _order.OId,
                OdPackageId = dto.pp_id,
                OdProductId = dto.ps_id,
            };

            _order_IOC._ordersDetails_EFCore.Add(_orderDetail);
            await _order_IOC._ordersDetails_EFCore.SaveChangesAsync();

            var room_iq = _order_IOC._room_EFCore.GetAll(d => d.RId == dto.r_id).SingleOrDefault();
            var employee_iq = _login_IOC._sysEmployee_EFCore.GetAll(d => d.EId == dto.e_id).SingleOrDefault();


            // 更新房间状态
            room_iq.RCurrentOccupancy += 1;
            if (room_iq.RCurrentOccupancy == room_iq.RTotalBeds)
            {
                room_iq.RStatus = 1;
            }

            // 更新理疗师状态
            employee_iq.ELeisure = 1;

            _order_IOC._room_EFCore.Update(room_iq);
            _login_IOC._sysEmployee_EFCore.Update(employee_iq);

            // 保存所有剩余变更
            await _order_IOC._room_EFCore.SaveChangesAsync();
            await _login_IOC._sysEmployee_EFCore.SaveChangesAsync();


            return Get_Result(1, "ok");

        }

        /// <summary>
        /// 修改预约状态
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Change_Appointment_Status(Appointment_Dto dto)
        {
            var iq = await _appointment_IOC._appointment_EFCore.GetAll(d => d.AId == dto.id).SingleOrDefaultAsync();

            iq.AStatus = dto.status ?? iq.AStatus;
            iq.ATime = dto.time ?? iq.ATime;

            _appointment_IOC._appointment_EFCore.Update(iq);
            _appointment_IOC._appointment_EFCore.SaveChangesAsync();

            return Get_Result(1, "修改成功");
        }

        /// <summary>
        /// 获取当天预约记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Appointment(Appointment_Dto dto)
        {
            var now = DateTime.Now.Date;
            // 预约表
            var data = await _appointment_IOC._appointment_EFCore.GetAll(out int total, dto.page, dto.limit, true, d => d.ATime, d => d.APeriod == now && d.AStatus == 0 && (d.ACustomerName.Contains(dto.key) || d.APhone.Contains(dto.key))).Select(d => new
            {
                id = d.AId,
                c_name = d.ACustomerName, // 预约姓名
                c_phone = d.APhone, // 预约电话
                time = d.ATime, // 预约时间
                p_sid = d.AProductId, // 产品规格id
                p_pid = d.APackageId, // 套餐id
            }).ToListAsync();

            // 产品规格
            var product_specs = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
            {
                p_sid = d.PsId, // 规格id
                p_id = d.PsProductId, // 产品id
            }).ToListAsync();

            // 产品
            var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
            {
                id = d.PId,
                name = d.PName,
            }).ToListAsync();

            // 套餐
            var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
            {
                id = d.PpId,
                name = d.PpName,
            }).ToListAsync();

            // 处理每个预约，获取总项目
            var resultData = data.Select(appointment =>
            {
                // 获取产品名称
                var productNames = new List<string>();
                if (!string.IsNullOrEmpty(appointment.p_sid))
                {
                    var productSpecIds = appointment.p_sid.Split(',').ToList();
                    var productIds = product_specs.Where(ps => productSpecIds.Contains(ps.p_sid)).Select(ps => ps.p_id).ToList();
                    productNames.AddRange(product.Where(p => productIds.Contains(p.id)).Select(p => p.name));
                }

                // 获取套餐名称
                var packageNames = new List<string>();
                if (!string.IsNullOrEmpty(appointment.p_pid))
                {
                    var packageIds = appointment.p_pid.Split(',').ToList();
                    packageNames.AddRange(package.Where(p => packageIds.Contains(p.id)).Select(p => p.name));
                }

                // 组合总项目
                var totalProject = string.Join(" + ", productNames.Concat(packageNames));

                return new
                {
                    id = appointment.id,
                    name = appointment.c_name,
                    time = appointment.time,
                    phone = appointment.c_phone,
                    totalProject = totalProject
                };
            }).ToList();

            return Get_Result(1, "ok", new
            {
                data = resultData,
                total = total
            });
        }

        /// <summary>
        /// 获取当天的未拨打预约
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Get_Inform_Appointment(Appointment_Dto dto)
        {
            var now = DateTime.Now.Date;
            // 预约表
            var data = await _appointment_IOC._appointment_EFCore.GetAll(out int total, dto.page, dto.limit, true, d => d.ATime, d => d.APeriod == now && d.AStatus == 0 && (d.ACustomerName.Contains(dto.key) || d.APhone.Contains(dto.key)) && d.AVisit==0).Select(d => new
            {
                id = d.AId,
                c_name = d.ACustomerName, // 预约姓名
                c_phone = d.APhone, // 预约电话
                time = d.ATime, // 预约时间
                p_sid = d.AProductId, // 产品规格id
                p_pid = d.APackageId, // 套餐id
            }).ToListAsync();

            // 产品规格
            var product_specs = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
            {
                p_sid = d.PsId, // 规格id
                p_id = d.PsProductId, // 产品id
            }).ToListAsync();

            // 产品
            var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
            {
                id = d.PId,
                name = d.PName,
            }).ToListAsync();

            // 套餐
            var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
            {
                id = d.PpId,
                name = d.PpName,
            }).ToListAsync();

            // 处理每个预约，获取总项目
            var resultData = data.Select(appointment =>
            {
                // 获取产品名称
                var productNames = new List<string>();
                if (!string.IsNullOrEmpty(appointment.p_sid))
                {
                    var productSpecIds = appointment.p_sid.Split(',').ToList();
                    var productIds = product_specs.Where(ps => productSpecIds.Contains(ps.p_sid)).Select(ps => ps.p_id).ToList();
                    productNames.AddRange(product.Where(p => productIds.Contains(p.id)).Select(p => p.name));
                }

                // 获取套餐名称
                var packageNames = new List<string>();
                if (!string.IsNullOrEmpty(appointment.p_pid))
                {
                    var packageIds = appointment.p_pid.Split(',').ToList();
                    packageNames.AddRange(package.Where(p => packageIds.Contains(p.id)).Select(p => p.name));
                }

                // 组合总项目
                var totalProject = string.Join(" + ", productNames.Concat(packageNames));

                return new
                {
                    id = appointment.id,
                    name = appointment.c_name,
                    time = appointment.time,
                    phone = appointment.c_phone,
                    totalProject = totalProject
                };
            }).ToList();

            return Get_Result(1, "ok", new
            {
                data = resultData,
                total = total
            });
        }


        /// <summary>
        /// 获取空闲员工(理疗师)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Employees()
        {
            var ids = _sys_IOC._sysDepartment_EFCore.GetAll(d => (d.DId == "81C9851D703E401396A52871925FD96A" || d.DParentId == "81C9851D703E401396A52871925FD96A")).Select(d => d.DId).ToList();

            var now = DateTime.Now.Date.ToString("yyyy-MM-dd");

            // 当前时间
            string hourMinute = DateTime.Now.ToString("HH:mm");

            // 先将所有当日排班的记录加载到内存中
            var allArrangements = _arrange_IOC._arrange_EFCore.GetAll(d => d.ADate == now).ToList();

            // 在内存中过滤出当前时间在时间段内的排班记录
            var sleep_id = allArrangements
                .Where(d => IsTimeInRange(d.ATimeRange, hourMinute))
                .Select(d => d.AEid)
                .ToList();

            // 将AEid字符串拆分成字符串数组
            var sleep_id_list = sleep_id.SelectMany(id => id.Split(',')).ToList();

            var data = await _login_IOC._sysEmployee_EFCore.GetAll(false, d => d.ECreateTime, d => d.EIsBan != 1 && ids.Contains(d.EDepartmentId) && sleep_id_list.Contains(d.EId) && d.ELeisure != 1).Select(d => new Employees_Dto
            {
                id = d.EId,
                name = d.EName,
            }).ToListAsync();

            return Get_Result(1, "ok", data);
        }

        // 判断当前时间是否在时间段内
        private bool IsTimeInRange(string timeRange, string currentTime)
        {
            // 解析时间段
            var parts = timeRange.Split('-');
            if (parts.Length != 2)
            {
                throw new ArgumentException("Invalid time range format.");
            }

            var startTime = TimeSpan.Parse(parts[0]);
            var endTime = TimeSpan.Parse(parts[1]);
            var current = TimeSpan.Parse(currentTime);

            // 判断当前时间是否在时间段内
            return current >= startTime && current <= endTime;
        }

        /// <summary>
        /// 获取员工(前台)
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Employees_Front()
        {
            var data = await _login_IOC._sysEmployee_EFCore.GetAll(false, d => d.ECreateTime, d => d.EIsBan != 1 && d.EPostId == "04091b06026d0002f34de68e7f180449").Select(d => new Employees_Dto
            {
                id = d.EId,
                name = d.EName,
            }).ToListAsync();

            return Get_Result(1, "ok", data);
        }

        /// <summary>
        /// 获取空闲房间
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Leisure_Room()
        {
            var data = await _order_IOC._room_EFCore.GetAll(false, d => d.RCreateTime, d => d.RStatus == 0 && d.RCurrentOccupancy != d.RTotalBeds && d.RIsBan != 1).Select(d => new Room_Dto
            {
                id = d.RId,
                name = d.RName,
                totalbeds = d.RTotalBeds,//总
                currentoccupancy = d.RCurrentOccupancy,//当前
                residue = d.RTotalBeds - d.RCurrentOccupancy,//余
                status = d.RStatus,
            }).ToListAsync();

            return Get_Result(1, "ok", data);
        }

        /// <summary>
        /// 获取所有支付方式
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Pay()
        {
            var data = await _sys_IOC._sysDictionary_EFCore.GetAll(false, d => d.DSort, d => d.DParentId == "04091b060257003b9190aa4ff663d34c" && d.DIsBan != 1).Select(d => new Dictionary_Dto
            {
                id = d.DId,
                name = d.DName,
                remark = d.DRemark,
                icon = d.DIcon,
            }).ToListAsync();

            return Get_Result(1, "ok", data);
        }

        /// <summary>
        /// 获取待安排的预约信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Plan_Appointment(Appointment_Dto dto)
        {
            var now = DateTime.Now.Date;
            // 预约表
            var data = await _appointment_IOC._appointment_EFCore.GetAll(out int total, dto.page, dto.limit, true, d => d.ATime, d => d.APeriod == now && d.AStatus == 1 && d.AIsOrder == 0).Select(d => new
            {
                id = d.AId,
                c_name = d.ACustomerName, // 预约姓名
                c_phone = d.APhone, // 预约电话
                time = d.ATime, // 预约时间
                p_sid = d.AProductId, // 产品规格id 逗号隔开
                p_pid = d.APackageId, // 套餐id 逗号隔开
                date = d.APeriod,
                money = d.AMoney,
            }).ToListAsync();

            // 产品规格
            var product_specs = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
            {
                p_sid = d.PsId, // 规格id
                p_id = d.PsProductId, // 产品id
            }).ToListAsync();

            // 产品
            var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
            {
                id = d.PId,
                name = d.PName,
            }).ToDictionaryAsync(d => d.id, d => d.name);

            // 套餐
            var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
            {
                id = d.PpId,
                name = d.PpName,
            }).ToDictionaryAsync(d => d.id, d => d.name);

            // 构造最终返回的数据格式
            var resultData = data.Select(d => new
            {
                id = d.id,
                name = d.c_name,
                time = d.time,
                date = d.date.Value.ToString("yyyy-MM-dd"),
                phone = d.c_phone,
                money = d.money,
                detail = new
                {
                    products = d.p_sid.Split(',').Select(psId =>
                    {
                        var spec = product_specs.FirstOrDefault(s => s.p_sid == psId);
                        if (spec != null && product.ContainsKey(spec.p_id))
                        {
                            return new { detailId = psId, detailName = product[spec.p_id] };
                        }
                        return null;
                    }).Where(p => p != null).ToList(),
                    packages = d.p_pid.Split(',').Select(ppId =>
                    {
                        if (package.ContainsKey(ppId))
                        {
                            return new { detailId = ppId, detailName = package[ppId] };
                        }
                        return null;
                    }).Where(p => p != null).ToList()
                }
            }).Where(r => (r.detail.products.Any() || r.detail.packages.Any()) && (r.name.Contains(dto.key) || r.phone.Contains(dto.key))) // 过滤掉没有 detail 的预约
            .ToList();

            return Get_Result(1, "ok", new
            {
                data = resultData,
                total = total
            });
        }

        /// <summary>
        /// 获取待支付的订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Plan_Order(Orders_Dto dto)
        {
            // 获取订单信息
            var orders = await _order_IOC._orders_EFCore.GetAll(false, d => d.OCreateTime, d => d.OOrderStatus != 1)
                .Select(d => new
                {
                    d.OId,
                    d.OCustomerName,
                    d.OCustomerId,
                    CreateTime = d.OCreateTime.Value.ToString("yyyy-MM-dd HH:mm"),
                    d.OCustomerPhone,
                    d.OTotalAmount,
                    d.OPayStatus,
                }).ToListAsync();

            // 获取订单详情
            var orderDetails = await _order_IOC._ordersDetails_EFCore.GetAll()
                .Select(d => new
                {
                    d.OdOrderId, // 对应订单表的订单id
                    OdProductIds = d.OdProductId != null ? d.OdProductId.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) : Array.Empty<string>(), // 拆分产品规格ID，处理null情况
                    OdPackageIds = d.OdPackageId != null ? d.OdPackageId.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) : Array.Empty<string>() // 拆分套餐ID，处理null情况
                }).ToListAsync();

            // 获取产品规格
            var productSpecs = await _product_IOC._productSpecs_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PsId, d => d.PsProductId);

            // 获取产品
            var products = await _product_IOC._product_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PId, d => d.PName);

            // 获取套餐
            var packages = await _product_IOC._productPackage_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PpId, d => d.PpName);

            // 构建最终的返回格式
            var result = orders.Select(order => new
            {
                id = order.OId,
                name = order.OCustomerName,
                time = order.CreateTime,
                phone = order.OCustomerPhone,
                money = order.OTotalAmount.ToString(),
                pay_status = order.OPayStatus,
                detail = new
                {
                    products = orderDetails
                        .Where(od => od.OdOrderId == order.OId)
                        .SelectMany(od => od.OdProductIds) // 展平产品规格ID
                        .Select(od => new
                        {
                            specId = od, // 产品规格ID
                            productId = productSpecs.TryGetValue(od, out var productId) ? productId : null // 获取产品ID
                        })
                        .Where(p => p.productId != null && products.ContainsKey(p.productId)) // 确保产品ID有效
                        .Select(p => new
                        {
                            detailId = p.specId, // 产品规格ID
                            detailName = products[p.productId] // 产品名字
                        }).ToList(),
                    packages = orderDetails
                        .Where(od => od.OdOrderId == order.OId)
                        .SelectMany(od => od.OdPackageIds) // 展平套餐ID
                        .Select(od => new
                        {
                            detailId = od,
                            detailName = packages.ContainsKey(od) ? packages[od] : null
                        })
                        .Where(p => p.detailName != null)
                        .ToList()
                }
            })
            .Select(order => new
            {
                id = order.id,
                name = order.name,
                time = order.time,
                phone = order.phone,
                money = order.money,
                pay_status = order.pay_status,
                detail = new
                {
                    products = order.detail.products.Any() ? order.detail.products : null,
                    packages = order.detail.packages.Any() ? order.detail.packages : null
                }
            })
            .Select(order =>
            {
                var detail = new Dictionary<string, object>();
                if (order.detail.products != null)
                {
                    detail.Add("products", order.detail.products);
                }
                if (order.detail.packages != null)
                {
                    detail.Add("packages", order.detail.packages);
                }
                return new
                {
                    id = order.id,
                    name = order.name,
                    time = order.time,
                    phone = order.phone,
                    money = order.money,
                    pay_status = order.pay_status,
                    detail = detail.Count > 0 ? detail : null
                };
            }).Where(i => i.name.Contains(dto.key) || i.phone.Contains(dto.key))
            .ToList();

            return Get_Result(1, "ok", result);
        }


        /// <summary>
        /// 获取所有房间
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Rooms()
        {
            var data = await _order_IOC._room_EFCore.GetAll(false, d => d.RStatus != 1).Select(d => new Room_Dto
            {
                id = d.RId,
                name = d.RName,
                totalbeds = d.RTotalBeds,//总
                currentoccupancy = d.RCurrentOccupancy,//当前
                residue = d.RTotalBeds - d.RCurrentOccupancy,//余
                status = d.RStatus,
                isban = d.RIsBan,
            }).ToListAsync();

            return Get_Result(1, "ok", data);
        }

        /// <summary>
        /// 确认订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Order_Ko(string id)
        {
            var iq = await _order_IOC._orders_EFCore.GetAll(d => d.OId == id).SingleOrDefaultAsync();
            iq.OOrderStatus = 1;
            iq.OCompleteTime = DateTime.Now;

            var room_iq = _order_IOC._room_EFCore.GetAll(d => d.RId == iq.ORoomId).SingleOrDefault();

            room_iq.RCurrentOccupancy -= 1;
            if (room_iq.RCurrentOccupancy != room_iq.RTotalBeds)
            {
                room_iq.RStatus = 0;
            }

            //理疗师
            var e_iq = _login_IOC._sysEmployee_EFCore.GetAll(d => d.EId == iq.OEmployeeArtId).SingleOrDefault();
            e_iq.ELeisure = 0;

            _login_IOC._sysEmployee_EFCore.Update(e_iq);
            await _login_IOC._sysEmployee_EFCore.SaveChangesAsync();

            _order_IOC._room_EFCore.Update(room_iq);
            await _order_IOC._room_EFCore.SaveChangesAsync();


            _order_IOC._orders_EFCore.Update(iq);
            await _order_IOC._orders_EFCore.SaveChangesAsync();

            return Get_Result(1, "ok");
        }

        /// <summary>
        /// 订单支付
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Order_Pay(Orders_Dto dto)
        {
            var iq = await _order_IOC._orders_EFCore.GetAll(d => d.OId == dto.id).SingleOrDefaultAsync();

            iq.OTotalAmount = Convert.ToDecimal(dto.money);
            iq.OPayType = dto.pay_id;
            iq.OPayStatus = 1;

            var iq_detail = _order_IOC._ordersDetails_EFCore.GetAll(d => d.OdOrderId == dto.id).SingleOrDefault();

            iq_detail.OdProductId = dto.ps_id;
            iq_detail.OdPackageId = dto.pp_id;

            _order_IOC._orders_EFCore.Update(iq);
            _order_IOC._ordersDetails_EFCore.Update(iq_detail);

            await _order_IOC._orders_EFCore.SaveChangesAsync();
            await _order_IOC._ordersDetails_EFCore.SaveChangesAsync();

            OrderPayment payment = new OrderPayment()
            {
                OpId = Config.GUID(),
                OpOid = dto.id,
                OpCreateTime = DateTime.Now,
                OpMoney = Convert.ToDouble(dto.money),
            };

            _order_IOC._ordersPay_EFCore.Add(payment);
            await _order_IOC._ordersPay_EFCore.SaveChangesAsync();

            return Get_Result(1, "ok");
        }

        /// <summary>
        /// 微信支付接口
        /// </summary>
        /// <returns></returns>
        public bool Pay()
        {
            return true;
        }

        /// <summary>
        /// 预约已通知
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Appointment_Inform(string id)
        {
            var iq = await _appointment_IOC._appointment_EFCore.GetAll(d => d.AId == id).SingleAsync();

            iq.AVisit = 1;

            _appointment_IOC._appointment_EFCore.Update(iq);
            await _appointment_IOC._appointment_EFCore.SaveChangesAsync();

            return Get_Result(1,"ok");
        }
    }
}
